/*===============================================
*   文件名称：tcp_server.c
*   创 建 者：
*   创建日期：2024年09月18日
*   描    述：
================================================*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <signal.h>

int main(int argc, char *argv[])
{
    signal(SIGPIPE, SIG_IGN);
    int listenfd = socket(AF_INET, SOCK_STREAM, 0);
    if (-1 == listenfd)
    {
        perror("socket");
        return -1;
    }

    struct sockaddr_in saddr;
    saddr.sin_family = AF_INET;
    saddr.sin_port = htons(8888);
    saddr.sin_addr.s_addr = htonl(INADDR_ANY); // 等价于inet_addr("0")

    if (-1 == bind(listenfd, (void *)&saddr, sizeof saddr))
    {
        perror("bind");
        return -1;
    }

    if (-1 == listen(listenfd, 10))
    {
        perror("listen");
        return -1;
    }

    puts("listen...");

    char buf[1024], pic_len[5] = {0};
    int ret;

    while (1)
    {
        int nfd = accept(listenfd, NULL, NULL);
        if (-1 == nfd)
        {
            continue;
        }
        int fd = open("img1.png", O_RDONLY);
        if (-1 == fd)
        {
            close(fd);
            continue;
        }
        while (1)
        {
            ret = read(fd, buf, 1024);
            sprintf(pic_len, "%d", ret);
            write(nfd, pic_len, 5);
            if (0 == ret)
                break;
            write(nfd, buf, ret);
        }
        close(fd);
        close(nfd);
    }

    return 0;
}
